package com.gtm.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gtm.config.SHA1;
import com.gtm.model.Topic;
import com.gtm.model.User;
import com.gtm.repository.TopicRepository;
import com.gtm.repository.UserRepository;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.*;

import static com.gtm.config.SHA1.encode;

/**
 * Created by 骆清波 on 2017/10/28.
 */
@Service
public class UserServicce extends BaseService<User>{
    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    UserRepository userRepository;

    @Autowired
    TopicRepository tpr;



    public User add(User user) {
        return userRepository.save(user);
    }

    public User findByUsernamePassword(String username, String password) {
        SHA1 sha1=new SHA1();
        String passwordSHA1=encode(password);
        User user=userRepository.findByUsernameAndPasswd(username,passwordSHA1);
        return user;
    }


    public List<User> findByType() {
        return userRepository.findByType((byte)1);
    }

    public void updateUser(String email, String password, String phone, String id,String sex) {
        SHA1 sha1=new SHA1();
        String passwordSHA1=sha1.encode(password);
        //System.out.println(passwordSHA1);
        User user=userRepository.findOne(id);
        BasicDBObject detailInfo=new BasicDBObject();
        if (null!=user.getDetail()){
            detailInfo=(BasicDBObject) user.getDetail();
        }
        detailInfo.put("email",email);
        detailInfo.put("phone",phone);
        detailInfo.put("sex",sex);
        user.setDetail(detailInfo);
        user.setPasswd(passwordSHA1);
        userRepository.save(user);
        //System.out.println(user);
    }

    public void updateUserWithSign(String id, String email, String password, String phone, String office, String level, String direction, String sex, MultipartFile sign) throws IOException {
        SHA1 sha1=new SHA1();
        String passwordSHA1=sha1.encode(password);
        User user=userRepository.findOne(id);
        BasicDBObject detailInfo=new BasicDBObject();
        if (null!=user.getDetail()){
            detailInfo=(BasicDBObject) user.getDetail();
        }
        detailInfo.put("email",email);
        detailInfo.put("phone",phone);
        detailInfo.put("office",office);
        detailInfo.put("level",level);
        detailInfo.put("direction",direction);
        detailInfo.put("sex",sex);
        String signpic=upUserFile(sign,user);
        detailInfo.put("sign",signpic);
        user.setDetail(detailInfo);
        user.setPasswd(passwordSHA1);
        userRepository.save(user);
        //System.out.println(user);
    }

    public User findByUsernameEmail(String username, String email) {

        return userRepository.findByUsernameAndEmail(username,email);
    }

    public User findById(String id) {
        return userRepository.findOne(id);
    }

    public void deltopic(String id) {
        User user=userRepository.findOne(id);
        user.setTopicId("");
        userRepository.save(user);
    }

    public List<User> listStudent(String tid,String topicChose,String stuName) {
        List<Topic> tpc=new ArrayList<Topic>();
        if(topicChose==null||topicChose.trim().equals(""))
            tpc=tpr.findByTeacherIdAndMarkedDel(tid,false);
        else
            tpc=tpr.findByIdAndMarkedDelAndTeacherId(topicChose,false,tid);
        if(tpc==null)
            return null;
        List<User> users=new ArrayList<User>();
        for(Topic t:tpc) {
            List<User> user=new ArrayList<User>();
            if(stuName==null||stuName.trim().equals(""))
                user=userRepository.findByTopicIdAndSelectTopicState(t.getId().toString(),"selected");
            else
                user=userRepository.findByTopicIdAndSelectTopicStateAndRealnameLike(t.getId().toString(),"selected",stuName);
            if(user!=null&&user.size()!=0) {
                users.addAll(user);
            }
        }
        return users;
    }

    public List<User> findStu() {
        return userRepository.findByType((byte) 0);
    }

    public User resetPassword(String username) {
        User user = userRepository.findByUsername(username);
        DBObject detail = user.getDetail();
        String to = detail.get("email").toString();
        String str =String.valueOf(Math.round(Math.random()*1000000));
        SHA1 sha1=new SHA1();
        String passwordSHA1=sha1.encode(str);
        System.out.println(str);
        user.setPasswd(passwordSHA1);
        // 发件人邮箱
        String from = "18658110625@163.com";

        // 指定发送邮件的主机
        String host = "smtp.163.com";

        // 获取系统属性
        Properties properties = System.getProperties();

        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);

        properties.put("mail.smtp.auth", "true");
        // 获取默认session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("18658110625@163.com", "z123456");
            }
        });

        try {
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);

            // Set From: 头部头字段
            message.setFrom(new InternetAddress(from));

            // Set To: 头部头字段
            message.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(to));

            // Set Subject: 头部头字段
            message.setSubject("毕业设计管理系统");

            // 设置消息体
            message.setText("你新的密码是" + str);

            // 发送消息
            Transport.send(message);
            System.out.println("Sent message successfully....from runoob.com");
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
        return userRepository.save(user);
    }

    public List<User> findByState(String state) {
        return userRepository.findByState(state);
    }

    public List<User> findByStateIn(List<String> state) {
        return userRepository.findByStateIn(state);
    }

    public Page<User> findByAddSta0teIn(PageRequest pageRequest,String state, String searchKey) {
        System.out.println(state+pageRequest.getPageSize()+pageRequest.getPageNumber());
        if(searchKey!=null)
            return userRepository.findByAddSta0teInWithSearchKey(pageRequest,state,searchKey);
        else
            return userRepository.findByAddSta0teIn(pageRequest,state);
    }

    public List<User> findByNotOfStu(String stuId) {
        User user=userRepository.findOne(stuId);
        String topicId=user.getTopicId();
        Topic tpc=tpr.findOne(topicId);
        String teacherId=tpc.getTeacherId();
        Byte type=(byte)1;
        List<User> userlist=userRepository.findByTypeIsAndIdNot(type,null);
        return userlist;
    }

    public User stuUploadThesis(String stuId, MultipartFile thesisFile) throws IOException {
        User user=userRepository.findOne(stuId);
        System.out.println(user.getAdditionalData());
//        if (user.getAdditionalData().get("state").toString().equals("GROUP_PASS")==false){
//            throw new RuntimeException("state error");
//        }
        String fileid=upUserFile(thesisFile,user);
        user.setAdditionalData("state","THESIS_PENDING");
        user.setAdditionalData("thesisFile",fileid);
        return userRepository.save(user);
    }

    public User auditThesis(String stuId, String grade, Boolean isPass) {
        User user=userRepository.findOne(stuId);
        user.setAdditionalData("thesis_grade",grade);
        if (isPass==true)
            user.setAdditionalData("state","THESIS_ONE_PASS");
        else
            user.setAdditionalData("state","GROUP_PASS");
        return userRepository.save(user);
    }
}
